<template>
    <div id="map-container" class="map" ref="mapRef"></div>
    <el-icon size="40">
        <Delete />
    </el-icon>
</template>
<script setup lang="ts" name="LeafMap">
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount, h } from "vue";
// import { useRoute } from 'vue-router'
import { Delete } from '@element-plus/icons-vue'
console.log(Delete)
import "leaflet-editable";
import 'leaflet/dist/leaflet.css'
import L from 'leaflet'

const mapRef = ref<HTMLDivElement>();
const route = {} //useRoute()
//data
let map: any,
    icons = '/money.png',
    Url = 'localhost:8000/mapservice/MapImageServer?Z=14&amp;C=13152&amp;R=6532&amp;Layer=shanxisl&amp;type=normal', //'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
    latLng = { lat: "34.26562", lng: "108.95351" },
    marker = "",
    NewUrl = '/sun.png',
    editlayers: any[] = [],
    boxSelection: any[] = [];
// emits
const emit = defineEmits(['getboxSelection', 'getLats']);

// onMounted
onMounted(() => {
    init();
})
onBeforeUnmount(() => {
    map.off()
    map.remove()
})
// methods
function init() {
    // const _this = this;
    map = L.map("map-container", {
        center: L.latLng(34.26562, 108.95351), // 地图中心
        zoom: 13, //缩放比列
        minZoom: 5,
        // minNativeZoom: 7,
        // zoomControl: false, //禁用 + - 按钮
        doubleClickZoom: false, // 禁用双击放大
        attributionControl: false, // 移除右下角leaflet标识
        // editable: true //地图编辑
    });
    // tileLayer 用于在地图上加载和显示瓦片图层。
    // {s} 是指可用的子域之一（按顺序使用，以帮助解决每个域的浏览器并行请求限制；子域值在选项中指定;默认为 a, b 或 c , 可以省略), {z} — 缩放级别, {x} 和 {y} — 瓦片坐标。 {r} 可以用来在URL中添加 "@2x" 以加载视网膜瓦片
    //let gaoDeLayer = L.tileLayer(window.mapUrl + "/mapservice/MapImageServer?Z={z}&C={x}&R={y}&Layer=shanxisl&type=normal", {});
    let gaoDeLayer = L.tileLayer(Url, { attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' });
    gaoDeLayer.addTo(map);
    // 定义控件
    L.EditControl = L.Control.extend({
        // 定义控件的参数
        options: {
            position: "topleft", // 地图的左上角
            callback: null,
            kind: "",
            html: ""
        },
        // 添加控件的内容（框选控件）
        onAdd(map: any) {
            let container = L.DomUtil.create("div", "leaflet-control leaflet-bar");
            let link = L.DomUtil.create("a", "", container);
            link.href = "#";
            link.title = "框选";
            link.innerHTML = this.options.html;
            L.DomEvent.on(link, "click", L.DomEvent.stop).on(
                link,
                "click",
                function () {
                    window.LAYER = this.options.callback.call(map.editTools);
                },
                this
            );
            return container;
        }
    });
    // 删除控件
    L.DeleteControl = L.Control.extend({
        options: {
            position: "topleft",
            callback: null,
            kind: "rectangle",
            html: "<i class='iconfont icon-del'> del </i>"
            // <el-icon size="40" >
            // <Delete/>
            // < /el-icon> 
            // "<i class='el-icon-delete'>del</i > "
        },
        onAdd(map: any) {
            // 创建一个class为'leaflet-control leaflet-bar'的div
            let container = L.DomUtil.create("div", "leaflet-control leaflet-bar");
            // 创建一个a标签悬停进行按钮提示
            let link = L.DomUtil.create("a", "", container);
            link.href = "#";
            link.title = "清除";
            // 设置显示的按钮图标
            link.innerHTML = this.options.html;
            // 处理dom点击事件（删除按钮的点击事件）
            L.DomEvent.on(link, "click", L.DomEvent.stop).on(
                link,
                "click",
                () => {
                    if (_this.$store.state.boxSelectionValue.length > 0) {
                        editlayers.forEach(item => {
                            map.removeLayer(item);
                        });
                        editlayers = [];

                        boxSelection = [];
                        _emit("getboxSelection", boxSelection);
                        _this.$store.commit("newboxSelectionValue", boxSelection);
                        sessionStorage.removeItem("boxSelection");
                        _emit("getLats", []);
                        sessionStorage.removeItem("baseList");
                    } else {
                        if (_editlayers.length > 0) {
                            _editlayers.forEach(item => {
                                sessionStorage.setItem("baseList", []);
                                map.removeLayer(item);
                            });
                            _editlayers = [];
                        }
                        boxSelection = [];
                        _emit("getboxSelection", boxSelection);
                        _this.$store.commit("newboxSelectionValue", boxSelection);
                        sessionStorage.removeItem("boxSelection");
                        _emit("getLats", []);
                        sessionStorage.removeItem("baseList");
                    }
                },
                this
            );
            return container;
        }
    });
    //  添加删除控件在地图上
    map.addControl(new L.DeleteControl());
    // 框选控件
    L.NewRectangleControl = L.EditControl.extend({
        options: {
            position: "topleft",
            callback: map.editTools.startRectangle,
            kind: "rectangle",
            html: "<i class='el-icon-edit'>edit</i>"
        }
    });
    //  添加编辑控件在地图上
    map.addControl(new L.NewRectangleControl());
    // ...................
    if (route.path === "/oneClickQuery") {
        let boxselectList = JSON.parse(sessionStorage.getItem("boxSelection"));
        if (boxselectList && boxselectList.length > 0) {
            var rec = L.rectangle(boxselectList).addTo(map);
            rec.enableEdit();
            editlayers.push(rec);
        }
    } else {
        if (this.$store.state.boxSelectionValue.length > 0) {
            var rec = L.rectangle(this.$store.state.boxSelectionValue).addTo(map);
            rec.enableEdit();
            editlayers.push(rec);
            // this.map.fitBounds(rec.getBounds())
            // rec.on("dbclick", L.DomEvent.stop).on("dbclick", rec.toggleEdit);
        }
    }
    // ...................
    // var rec = L.rectangle([
    //   [43.1235, 1.255],
    //   [43.1235, 1.259],
    // ]).addTo(this.map);
    // rec.enableEdit();
    // rec.on("dbclick", L.DomEvent.stop).on("dbclick", rec.toggleEdit);
    // 绘图
    map.editTools.on("editable:drawing:end", e => {
        // let arr = [];
        // e.layer._latlngs[0].forEach((item) => {
        //   arr.push({ lat: item.lat, lon: item.lng });
        // });
        // e.layer._latlngs[0].forEach((item) => {
        //   item.__vertex.dragging.disable();
        // });
        editlayers.forEach(item => {
            // 在地图上移除给定的图层
            map.removeLayer(item);
        });
        // editlayers.push(e.layer);
        // this.getStations(e);
    });
    // 顶点拖动
    map.editTools.on("editable:vertex:dragend", e => {
        // editlayers.forEach((item) => {
        //   this.map.removeLayer(item);
        // });

        editlayers.push(e.layer);
        getStations(e);
    });
};
// 定位
function dingwei(val: any) {
    if (val[0].lat !== "" && val[0].lat !== null && val[0].lon !== "" && val[0].lon !== null) {
        map.eachLayer((layer: any) => {
            if (layer.options.icon) {
                if (layer.options.icon.options.iconUrl === NewUrl) {
                    layer.setIcon(
                        L.icon({
                            iconUrl: icons,
                            iconSize: [20, 20]
                        })
                    );
                }
                let pos = layer.getLatLng();
                if (pos.lat == val[0].lat && pos.lng == val[0].lon) {
                    layer.setIcon(
                        L.icon({
                            iconUrl: NewUrl,
                            iconSize: [30, 30]
                        })
                    );
                }
            }
            map.panTo([val[0].lat, val[0].lon], {
                animate: true
            });
        });
    } else {
        this.$message("该数据没有基站信息");
    }
};
// 提取经纬度
function getLats(val: any) {
    let arr: any = [];
    val.layer._latlngs[0].forEach((item: any) => {
        arr.push({ lat: item.lat, lon: item.lng });
    });
    return arr;
};
function getposition(val: any) {
    map.panTo([val.lat, val.lon], {
        animate: true
    });
};
async function getStations(val: any) {
    boxSelection = getLats(val);
    emit("getboxSelection", boxSelection);

    let latList = getLats(val);
    // const { data: res } = await getBaseStations({
    //     query_data: JSON.stringify(latList)
    // });
    // if (res.statusCode === "0") {
    //     if (res.data.list.length === 0) {
    //         this.$message.error("框选区域无基站，请重新框选");
    //         this.map.removeLayer(val.layer);
    //     } else if (res.data.list.length > 100) {
    //         this.$message.error("框选区域包含基站过多，请重新框选");
    //         this.map.removeLayer(val.layer);
    //     } else {
    //         let baseList = [];
    //         res.data.list.forEach(item => {
    //             baseList.push({ tac: item.lac, uli: item.ci });
    //         });
    //         emit("getLats", baseList);
    //     }
    // }
};
// 清除框选
function clear() {
    if (editlayers.length > 0) {
        editlayers.forEach(item => {
            this.map.removeLayer(item);
        });
        editlayers = [];
    }
}

</script>
<style>
@import url("/fontstyle/iconfont.css");

.map {
    width: 100%;
    /* height: 100%; */
    height: calc(100vh - 400px);
    border: 1px solid red
}

.toolclick {
    background: rgba(0, 0, 0, 0.7);
    color: #fff;
    border-color: rgba(0, 0, 0, 0.1);
    padding: 10px 18px;
    z-index: 99;
    font-size: 14px;
}

.TooltipAdress {
    display: flex;
}

.location {
    width: 150px;
    word-wrap: break-word;
    word-break: break-all;
    white-space: pre-wrap;
}

.contentHighlight {
    /* padding: 5px; */
    /* background: pink; */
    /* margin-top: 5px; */
    width: 25px !important;
    height: 25px !important;
    /* border: 1px solid red; */
    border-radius: 50%;
    margin-left: -18px !important;
    margin-top: -27px !important;
    /* -webkit-animation-name: "ripple";
  -webkit-animation-duration: 2s;
  -webkit-animation-timing-function: ease;
  -webkit-animation-delay: 0s;
  -webkit-animation-iteration-count: infinite;
  -webkit-animation-direction: alternate; */
}
</style>